#!/usr/bin/env python
# -*-coding:UTF-8 -*-
'''
@Project ：爬虫-波波老师
@File：21-模拟登录.py
@Author ：文非
@Date：2021/3/1217:06
@Require：# - 模拟登录    --- 人人网进行模拟登录
'''
# http://www.renren.com
# 需求： 对人人网进行模拟登录
#     - 点击登录按钮之后会发起一个post请求
#     - post请求中会携带登录之前录入的相关的登录信息（用户名，密码，验证码.....）
#     - 验证码每次请求都会动态变化

# 编码流程
    # 1 验证码识别 获取验证码图片文字数据
    # 2 对post请求进行发送（处理请求参数）
    # 3 对响应数据进行持久化存储

import requests
from lxml import etree
from chaojiying import Chaojiying_Client

def define(username, pwd, itemid):
    """验证码识别"""
    chaojiying = Chaojiying_Client(username, pwd, itemid)  # 用户中心>>软件ID 生成一个替换 96001
    chaojiying = Chaojiying_Client('zwwlx1013', 'zwwlx1013', '913953')  # 用户中心>>软件ID 生成一个替换 96001
    im = open('./rencode.jpg', 'rb').read()  # 本地图片文件路径 来替换 a.jpg 有时WIN系统须要//
    define_res = chaojiying.PostPic(im, 2004)['pic_str']
    return define_res

def main():
    # UA伪装
    headers = {
        'User-Agent': "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"
    }
    # 验证码获取
        # 1.指定url
    url = "http://www.renren.com"
        # 2.对验证码所在的首页发送请求
    response = requests.get(url=url, headers=headers)
        # 3.获取相应的页面数据
    define_text = response.text
        # 4.实例化一个etree对象
    tree = etree.HTML(define_text)
        # 5.解析验证码的img的src地址
    define_url = tree.xpath('//*[@id="verifyPic_login"]/@src')[0]
        # 6.拼接验证码url
        # 7.对拼接的url发送请求
    define_response = requests.get(url=define_url, headers=headers)
        # 8.获取返回的二进制图片数据
    define_data = define_response.content
        # 9.持久化保存到本地 将获取的结果当做模拟登录按钮的post请求的参数
    with open("./rencode.jpg","wb")as fp:
        fp.write(define_data)
    # 使用打码平台 对验证码识别
    username = 'zwwlx1013'
    pwd = 'zwwlx1013'
    itemid = '913953'
    result = define(username,pwd,itemid)
    print(result)
    login_url = "http://www.renren.com/ajaxLogin/login?1=1&uniqueTimestamp=2021251841290"
    data = {
        "email": "13476923553",
        "icode": result,
        "origURL": "http://www.renren.com/home",
        "domain": "renren.com",
        "key_id": "1",
        "captcha_type": "web_login",
        "password": "7e0defa8aed7f83ce67a662e597666ddc64a922efbd84b578a2232393c725031",
        "rkey": "1d3194e45e36088805d3b4378274ef78",
        "f": "http%3A%2F%2Fwww.renren.com%2F975503334"
    }
    login_after_page = requests.post(url=login_url, data=data, headers=headers).text
    # print(login_after_page)
    print(login_after_page.split("\"")[5])
    login_after_page = login_after_page.split("\"")[5]
    home_url = login_after_page
    home_page_response = requests.get(url=home_url,headers=headers)
    home_page = home_page_response.text
    response_code = home_page_response.status_code
    # print(home_page)
    print(response_code)

    with open("./renren.html", "w", encoding="utf-8")as fp:
        fp.write(login_after_page)

if __name__ == "__main__":

    main()

